package com.xin.uploadanddownload.controller;

import com.xin.uploadanddownload.model.FileVo;
import com.xin.uploadanddownload.model.MultipartFileParam;
import com.xin.uploadanddownload.service.FileService;
import com.xin.uploadanddownload.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
@CrossOrigin
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private StorageService storageService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }
    @PostMapping("/upload")
    @ResponseBody
    public FileVo upload(MultipartFile file) throws IOException {
        //调用service中的业务方法
        FileVo fileVO = fileService.upload(file);
        return fileVO;
    }
    @GetMapping("/downloadFile")
    @ResponseBody
    public Object downloadFile(HttpServletResponse response, String filePath) throws IOException {
        // 清空输出流
        response.reset();
        // 能实现断点下载，如果用户在下载过程中意外中断，需要重新下载整个文件
        response.setContentType("application/x-download;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String s = new String(filePath.getBytes("utf-8"));

        response.setHeader("Content-Disposition", "attachment;filename*=''"+ new String(filePath.getBytes("utf-8")));
        fileService.download(response.getOutputStream(),filePath);
        return null;
    }

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity fileUpload(@RequestPart("param") MultipartFileParam param,  @RequestPart("file") MultipartFile file ,HttpServletRequest request) {

        param.setFile(file);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            log.info("上传文件start。");
            try {
                // 方法1
                storageService.uploadFileRandomAccessFile(param);
                // 方法2 这个更快点
                storageService.uploadFileByMappedByteBuffer(param);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("文件上传失败。{}", param.toString());
            }
            log.info("上传文件end。");
        }
        return ResponseEntity.ok().body("上传成功。");
    }





}
